<template>
	<view>
		<u-navbar :border-bottom="false"></u-navbar>
		<view class="step1" v-if="step==0">
			<view class="content">
				<view class="title">
					<view class="u-font-60 text-bold">手机号登录/注册</view>
					<view class="text-gray u-m-t-20 u-font-28" @longpress="step=1">欢迎登录司空密信</view>
				</view>
				<view>
					<view class="phone-row u-flex">
						<view class="u-flex u-m-r-30 u-font-36" @tap="areaPicker.show=true">
							<text class="" style="font-size: 32rpx;">+</text><!-- ﹢ -->
							<text class="" style="padding-right:15rpx;">{{areaCode}}</text>
							<u-icon name="arrow-down" color="#666" size="26"></u-icon>
						</view>
						<input class="u-font-40" maxlength="20" type="number" v-model="phone" placeholder="请输入手机号" @blur="checkPhone" />
					</view>
					<view class="tips" :class="{error:phoneStatus.error}">{{phoneStatus.des}}</view>
				</view>
				<view v-show="captcha.must">
					<view class="u-flex">
						<input class="input u-flex-1" maxlength="11" type="text" v-model="captcha.code"
							placeholder="请输入图形码" @blur="checkCaptcha"/>
						<view @tap="getCaptcha" class="img-code u-m-l-20"
							:style="`background-image: url(data:image/png;base64,${captcha.base64})`"></view>
					</view>
					<view class="tips" :class="{error:imgStatus.error}">{{imgStatus.des}}</view>
				</view>
		
				<button @tap="sendSms" class="getCaptcha" :class="{valid:sendable}">获取短信验证码</button>
				<!-- <view class="alternative">
					<navigator open-type="navigateBack" class="password">密码登录</navigator>
					<view class="issue">遇到问题</view>
				</view> -->
			</view>
			<view class="u-flex u-row-center u-m-t-50">
				<u-checkbox v-model="agree" shape="circle">
					<text class="text-gray u-font-26">
						登录即表明同意
						<text class="text-blue" @tap.stop="jumpTo('/pages/agreement/agreement?id=shiyong')">《用户使用协议》</text>
						和
						<text class="text-blue" @tap.stop="jumpTo('/pages/agreement/agreement?id=yinsixieyi')">《隐私条款》</text>
					</text>
				</u-checkbox>
			</view>
		</view>
		<view class="step2" v-if="step==1">
			<view class="key-input">
				<view class="title">输入验证码</view>
				<view class="tips text-gray">验证码已发送至 <text class="text-black u-m-l-10">{{phone}}</text></view>
				<view class="code-input">
					<view class="item" v-for="(char,index) in maxlength" :key="index">
						{{verCode[index]||''}}
					</view>
					<input :auto-focus="true" class="hide-input" type="number" :maxlength="maxlength" v-model="verCode" @input="onInput"/>
				</view>
				<text :class="{ error: verStatus.error }">{{verStatus.des}}</text>
				<view class="captcha u-text-right" :class="{'text-gray':verStatus.second}">
					<text @tap="resend">重新发送{{ verStatus.second>0?`(${verStatus.second})`:'' }}</text>
					<!-- <text :class="{ noCaptcha: !verStatus.second }" @tap="resend">重新发送</text> -->
					<!-- <text :class="{ regain: verStatus.second }">重新发送({{ verStatus.second }})</text> -->
				</view>
			</view>
		</view>
		<u-select v-model="areaPicker.show" mode="single-column" :list="areaPicker.list" @confirm="changeAreaCode"></u-select>
	</view>
</template>

<script>
	import {sendSms,getImageCode,loginOrRegister,mustCaptcha} from "@/api/user.js"
	import {toast,goback,delay,jumpTo} from "@/utils/util.js"
	import {isValidPhone} from '@/utils/check.js'
	import {mapActions} from 'vuex'
	import areaCodes from "@/utils/areaCodes.js"
	export default {
		data() {
			return {
				step: 0,
				areaCode:'86',
				phone:'',
				areaPicker:{
					show:false,
					list:areaCodes.map(({name,code})=>({label:`${name} ﹢${code}`,value:code}))
				},
				
				phoneStatus:{
					valid:false,
					error:false,
					des:''
				},
				imgStatus: {
					error: false,
					des: ''
				},
				agree:false,
				
				maxlength: 4,
				verCode:'',
				verStatus:{
					second: 0,
					error:false,
					des:''
				},
				captcha:{ 
					must:false,
					token:'', 
					base64:'', 
					code:'' 
				}
			};
		},
		computed:{
			sendable(){
				return !!this.phone
			}
		},
		methods:{
			jumpTo,
			...mapActions('user',['login']),
			async getCaptcha() {
				const {
					imageBase64,
					token
				} = await getImageCode();
				this.captcha.base64 = imageBase64
				this.captcha.token = token;
			},
			async checkAgree() {
				if (!this.agree) {
					// #ifdef APP-PLUS
					uni.vibrateShort()
					// #endif
					throw toast('请勾选同意协议')
				}
			},
			async checkPhone(){
				if(!this.phone){
					this.phoneStatus.error=true
					this.phoneStatus.des = '请输入手机号'
					this.phoneStatus.valid=false
					throw new Error('请输入手机号')
				}
				
				
				
				
				
				
				this.phoneStatus.error=false
				this.phoneStatus.des = ''
				this.phoneStatus.valid=true;
				return true;
			},
			async checkCaptcha() {
				if(!this.captcha.must){
					return true
				}
				if(!this.captcha.code){
					this.imgStatus.error = true;
					this.imgStatus.des = '请输入图形码'
					throw new Error('请输入图形码')
				}
				this.imgStatus.error = false;
				this.imgStatus.des = ''
				return true;
			},
			async sendSms() {
				await Promise.all([this.checkAgree(),this.checkPhone(),this.checkCaptcha()])
				if(this.sendSms.lock){
					return
				}
				try{
					this.sendSms.lock = true
					
					
					// const mobile = `${this.areaCode=='86'?'':this.areaCode}${this.phone}`
					var phone = await this.handlePhone();
					const mobile = `${this.areaCode=='86'?'':'+'+this.areaCode}${phone}`
					const {time,status,message} = await sendSms({
						mobile:mobile,
						type:'login',
						imgToken: this.captcha.token,
						imgCode: this.captcha.code,
					})
					if(!status){
						return toast(message||'发送失败')
					}
					this.verStatus.second = time;
					this.step=1;
					const timer = setInterval(()=>{
						if(this.verStatus.second==0){
							clearInterval(timer)
						}else{
							this.verStatus.second--
						}
					},1000)
				}finally{
					this.sendSms.lock = false
				}
			},
			async resend(){
				if(this.verStatus.second>0){
					return 
				}
				this.sendSms()
				
				
				
				
				
				
				
				
				
				
			},
			
			onInput({detail:{value}}){
				this.verCode = value
				if (String(value).length > this.maxlength) return;
				if (String(value).length == this.maxlength) {
					this.finish()
				}
			},
			async finish(value) {
				console.log(value);
				if(this.finish.lock){
					return
				}
				try{
					var phone = await this.handlePhone();
					this.finish.lock = true
					const mobile = `${this.areaCode=='86'?'':'+'+this.areaCode}${phone}`
					const {
						token,
						userInfo,
						isNewUser,
						setPwd
					} = await loginOrRegister({mobile:mobile,verCode:this.verCode})
					
					if(setPwd){
						const {password} = await this.improvePwd(token)
						console.log(password)
						await delay(500)
						const {userName,avatarUrl} = await this.improveAvatar(token)
						console.log(userName,avatarUrl)
						userInfo.avatarUrl = avatarUrl
						userInfo.userName = userName
						await delay(500)
					}
					// if(/default_head.jpeg$/.test(userInfo.avatarUrl)){
					// }
					
					await this.login({
						token,
						userInfo
					})
					uni.showToast({
						title: '登录成功',
						duration: 1000
					});
					console.log(token);
					console.log(userInfo);
					await delay(1000)
					
					const routes = getCurrentPages()
					if(routes.length == 3){
						uni.navigateTo({
							url:'pages/improve/avatar',
						})
					}else{
						uni.reLaunch({
							url: '/pages/index/index',
						})
					}
					
					
						// goback(2)
					
				}catch(e){
					this.verCode = ''
				}finally{
					this.finish.lock = false
				}
			},
			handlePhone(){
				return new Promise((resolve,reject)=>{
					var phone = this.phone;
					if (phone.charAt(0) === '0') {
						phone = phone.substring(1);
					}
					resolve(phone);
				})
			},
			changeAreaCode([{value}]){
				this.areaCode = value
			},
			improveAvatar(token){
				return new Promise((resolve,reject)=>{
					uni.navigateTo({
						url:`/pages/improve/avatar?token=${token}`,
						events:{
							successful:resolve
						},
						fail:reject,
						success(){
							
						}
					})
				})
			},
			improvePwd(token){
				return new Promise((resolve,reject)=>{
					uni.navigateTo({
						url:`/pages/improve/password?token=${token}`,
						events:{
							successful:resolve
						},
						fail:reject,
						success(){
							
						}
					})
				})
			},
			improvePhone(token){
				return new Promise((resolve,reject)=>{
					uni.navigateTo({
						url:`/pages/improve/phone?token=${token}`,
						events:{
							successful:resolve
						},
						fail:reject,
						success(){
							
						}
					})
				})
			}
		}
	}
</script>
<style>
	page{
		background-color: #ffffff;
	}
</style>
<style lang="scss" scoped>
	$text-color:#FFFFFF;
	$error-color:#ff0000;
	.step1 {

		.content {
			width: 600rpx;
			margin: 80rpx auto 0;

			.img-code {
				flex: 0;
				min-width: 140rpx;
				height: 70rpx;
				background-size: auto 100%;
				background-repeat: no-repeat;
			}

			.title {
				margin-bottom: 100rpx;
			}

			.input {
				text-align: left;
				margin-bottom: 10rpx;
				padding-bottom: 6rpx;
				font-size: 40rpx;
			}

			.tips {
				color: $text-color;
				margin-bottom: 60rpx;
				margin-top: 8rpx;
				font-size: 20rpx;

				&.error {
					color: $error-color
				}
			}

			.getCaptcha {
				background-color: lighten($color: #436bed,$amount:20);
				color: $text-color;
				border: none;
				font-size: 30rpx;
				padding: 12rpx 0;

				&.valid {
					color: rgb(255, 255, 255);
					background-color: #436bed;
				}

				&::after {
					border: none;
				}
			}

			.alternative {
				color: $text-color;
				display: flex;
				justify-content: space-between;
				margin-top: 30rpx;
			}
		}
	}
	.step2 {
		padding: 80rpx;
		.key-input {
			padding: 30rpx 0;
			.error {
				display: block;
				color: red;
				font-size: 30rpx;
				margin: 20rpx 0;
			}
		}
		.title {
			font-size: 50rpx;
		}
		.tips {
			font-size: 30rpx;
			margin-top: 20rpx;
			margin-bottom: 60rpx;
		}
		.captcha {
			font-size: 30rpx;
			margin-top: 40rpx;
		}
	}
	.code-input{
		position: relative;
		overflow: hidden;
		display: flex;
		justify-content: space-between;
		.hide-input{
			position: absolute;
			top: 0;
			left: 0;
			transform: translateX(-50%);
			background-color: transparent;
			color: transparent;
			border: none;
			width: 200%;
			height: 100%;
		}
		.item{
			width: 100rpx;
			height: 100rpx;
			line-height: 100rpx;
			text-align: center;
			background-color: #F5F5F5;
			font-size: 50rpx;
			border-radius: 20rpx;
		}
	}
</style>